package pattern.structure.proxy.dynamic.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author : Rookie
 * @description : jdk动态代理
 * @date : 2023/10/1
 */
public class JdkDynamicProxy {

    public static void main(String[] args) {
        Calculate calculate = new CalculateImpl();
        Calculate proxyInstance = (Calculate) Proxy.newProxyInstance(calculate.getClass().getClassLoader(),
                calculate.getClass().getInterfaces(),
                new JdkInvocationHandler(calculate));
        int result = proxyInstance.add(1, 2);
        System.out.println(result);
        System.out.println("原始类型是" + calculate.getClass().getName());
        System.out.println("代理类型是" + proxyInstance.getClass().getName());
    }
}

interface Calculate {

    int add(int x,int y);
}


class CalculateImpl implements Calculate {


    @Override
    public int add(int x, int y) {
        System.out.println("执行具体业务");
        return x+y;
    }
}

class JdkInvocationHandler implements InvocationHandler {

    public Object obj;

    public JdkInvocationHandler(Object obj) {

        this.obj = obj;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("动态代理执行之前");
        Object obj = method.invoke(this.obj, args);
        System.out.println("动态代理执行之后");
        return obj;
    }
}
